<template>
  <div class="circular-chart">
    <h2>班级学生画像</h2>
    <div id="circular-chart" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted } from 'vue';
import * as echarts from 'echarts';

export default defineComponent({
  props: {
    data: {
      type: Object,
      required: true
    }
  },
  setup(props) {
    onMounted(() => {
      const chartDom = document.getElementById('circular-chart');
      const myChart = echarts.init(chartDom);

      const { totalStudents, subjectDistribution } = props.data;

      const option = {
        tooltip: {
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: Object.keys(subjectDistribution)
        },
        series: [
          {
            name: '学科分布',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '30',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: Object.entries(subjectDistribution).map(([name, value]) => ({
              name,
              value
            }))
          }
        ]
      };

      myChart.setOption(option);

      // 显示总人数
      myChart.on('finished', () => {
        const centerLabel = echarts.graphic.createElement(
          'text',
          {
            style: {
              text: `${totalStudents}\n人`,
              x: 'center',
              y: 'center',
              fill: '#333',
              fontSize: 20,
              textBaseline: 'middle',
              textAlign: 'center'
            }
          }
        );
        myChart.group.add(centerLabel);
      });

      window.addEventListener('resize', () => {
        myChart.resize();
      });
    });
  }
});
</script>

<style scoped>
.circular-chart {
  width: 100%;
}
</style>
